import React, {useState} from 'react';
import {Button, Form, Input, Modal, Radio, Tree} from 'antd';
import {DeleteOutlined, EditOutlined, FileOutlined, FolderOutlined, PlusOutlined} from '@ant-design/icons';

const { DirectoryTree } = Tree;
const { Search } = Input;

/**
 * 文件树示例
 * @constructor
 */
const FileTree = () => {
    const [treeData, setTreeData] = useState([
        {
            id: '1',
            title: '项目文件夹',
            key: '0-0',
            children: [
                {
                    id: '1-1',
                    title: 'src',
                    key: '0-0-0',
                    children: [
                        { title: 'index.js', key: '0-0-0-0', icon: <FileOutlined /> },
                        { title: 'App.js', key: '0-0-0-1', icon: <FileOutlined /> },
                        { title: 'components', key: '0-0-0-2', icon: <FolderOutlined /> },
                    ],
                },
                {
                    title: 'public',
                    key: '0-0-1',
                    children: [
                        { title: 'index.html', key: '0-0-1-0', icon: <FileOutlined /> },
                        { title: 'favicon.ico', key: '0-0-1-1', icon: <FileOutlined /> },
                    ],
                },
                { title: 'package.json', key: '0-0-2', icon: <FileOutlined /> },
            ],
        },
    ]);


    const [expandedKeys, setExpandedKeys] = useState<any>(['0-0']);
    const [selectedKeys, setSelectedKeys] = useState([]);
    const [autoExpandParent, setAutoExpandParent] = useState(true);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isEditModalVisible, setIsEditModalVisible] = useState(false);
    const [currentNode, setCurrentNode] = useState(null);
    const [form] = Form.useForm();

    // 展开/收起节点时触发
    const onExpand = (expandedKeys) => {
        setExpandedKeys(expandedKeys);
        setAutoExpandParent(false);
    };

    // 点击节点时触发
    const onSelect = (selectedKeys, { node }) => {
        setSelectedKeys(selectedKeys);
        setCurrentNode(node);

        const allChildKeys = getAllChildKeys(node);
        const allKeysIncludingCurrent = [node.key, ...allChildKeys];
        // 存入状态或用于后续操作
        console.log(allKeysIncludingCurrent)
    };

    // 递归收集所有子节点的 key
    const getAllChildKeys = (node) => {
        let keys = [];
        if (node.children && node.children.length > 0) {
            node.children.forEach(child => {
                keys.push(child.key);
                keys = keys.concat(getAllChildKeys(child)); // 递归查找子节点
            });
        }
        return keys;
    };

    // 更新树数据
    const updateTreeData = (list, key, children) => {
        return list.map(node => {
            if (node.key === key) {
                return {
                    ...node,
                    children,
                };
            }
            if (node.children) {
                return {
                    ...node,
                    children: updateTreeData(node.children, key, children),
                };
            }
            return node;
        });
    };

    // 添加新文件夹或文件
    const handleAdd = () => {
        form.resetFields();
        setIsModalVisible(true);
    };

    // 编辑文件夹或文件
    const handleEdit = () => {
        if (currentNode) {
            form.setFieldsValue({
                name: currentNode.title,
                type: currentNode.children ? 'folder' : 'file',
            });
            setIsEditModalVisible(true);
        }
    };

    // 删除节点
    const handleDelete = () => {
        if (currentNode) {
            Modal.confirm({
                title: '确认删除',
                content: `确定要删除 ${currentNode.title} 吗？`,
                onOk: () => {
                    const loop = (data) => {
                        return data.filter(node => {
                            if (node.key === currentNode.key) {
                                return false;
                            }
                            if (node.children) {
                                node.children = loop(node.children);
                            }
                            return true;
                        });
                    };
                    setTreeData(loop(treeData));
                    setSelectedKeys([]);
                },
            });
        }
    };

    // 提交添加/编辑表单
    const handleSubmit = () => {
        form.validateFields().then(values => {
            const { name, type } = values;
            const isFolder = type === 'folder';
            const icon = isFolder ? <FolderOutlined /> : <FileOutlined />;

            if (isEditModalVisible) {
                // 编辑节点
                const newNode = {
                    ...currentNode,
                    title: name,
                    icon,
                };

                const loop = (data) => {
                    return data.map(node => {
                        if (node.key === currentNode.key) {
                            return newNode;
                        }
                        if (node.children) {
                            return {
                                ...node,
                                children: loop(node.children),
                            };
                        }
                        return node;
                    });
                };

                setTreeData(loop(treeData));
                setIsEditModalVisible(false);
            } else {
                // 添加节点
                if (currentNode) {
                    const parentKey = currentNode.key;
                    const newKey = `${parentKey}-${Date.now()}`;

                    const newNode = {
                        title: name,
                        key: newKey,
                        icon,
                        isLeaf: !isFolder,
                    } as any;

                    if (isFolder) {
                        newNode.children = [];
                    }

                    const loop = (data) => {
                        return data.map(node => {
                            if (node.key === parentKey) {
                                return {
                                    ...node,
                                    children: node.children ? [...node.children, newNode] : [newNode],
                                };
                            }
                            if (node.children) {
                                return {
                                    ...node,
                                    children: loop(node.children),
                                };
                            }
                            return node;
                        });
                    };

                    setTreeData(loop(treeData));
                    setIsModalVisible(false);
                    setSelectedKeys([newKey]);
                }
            }
        });
    };

    // 搜索功能
    const onSearch = (value) => {
        const expandedKeys = treeData
            .map(item => {
                const matchNode = (node) => {
                    if (node.title.includes(value)) {
                        return true;
                    }
                    if (node.children) {
                        return node.children.some(child => matchNode(child));
                    }
                    return false;
                };
                return matchNode(item) ? item.key : null;
            })
            .filter(item => item !== null);

        setExpandedKeys(expandedKeys);
        setAutoExpandParent(true);
        setSelectedKeys([]);
    };

    React.useEffect(() => {
    }, []);

    return (
        <div style={{ padding: '20px', maxWidth: '400px' }}>
            <div style={{ marginBottom: '16px', display: 'flex', gap: '8px' }}>
                <Search
                    placeholder="搜索文件"
                    allowClear
                    onSearch={onSearch}
                    style={{ width: 200 }}
                />
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    添加
                </Button>
                <Button icon={<EditOutlined />} onClick={handleEdit} disabled={!currentNode}>
                    编辑
                </Button>
                <Button danger icon={<DeleteOutlined />} onClick={handleDelete} disabled={!currentNode}>
                    删除
                </Button>

                <Button onClick={() => {
                    console.log("-> currentNode", currentNode);
                }}>
                    输出
                </Button>
            </div>

            <DirectoryTree
                showIcon
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                selectedKeys={selectedKeys}
                onExpand={onExpand}
                onSelect={onSelect}
                treeData={treeData}
            />

            <Modal
                title="添加文件夹"
                visible={isModalVisible}
                onOk={handleSubmit}
                onCancel={() => setIsModalVisible(false)}
            >
                <Form form={form} layout="vertical">
                    <Form.Item
                        name="name"
                        label="名称"
                        rules={[{ required: true, message: '请输入名称' }]}
                    >
                        <Input placeholder="请输入名称" />
                    </Form.Item>
                    <Form.Item
                        name="type"
                        label="类型"
                        rules={[{ required: true, message: '请选择类型' }]}
                    >
                        <Radio.Group>
                            <Radio value="folder">文件夹</Radio>
                            <Radio value="file">文件</Radio>
                        </Radio.Group>
                    </Form.Item>
                </Form>
            </Modal>

            <Modal
                title="编辑文件/文件夹"
                visible={isEditModalVisible}
                onOk={handleSubmit}
                onCancel={() => setIsEditModalVisible(false)}
            >
                <Form form={form} layout="vertical">
                    <Form.Item
                        name="name"
                        label="名称"
                        rules={[{ required: true, message: '请输入名称' }]}
                    >
                        <Input placeholder="请输入名称" />
                    </Form.Item>
                    <Form.Item
                        name="type"
                        label="类型"
                        rules={[{ required: true, message: '请选择类型' }]}
                    >
                        <Radio.Group>
                            <Radio value="folder">文件夹</Radio>
                        </Radio.Group>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default FileTree;